package com.shanshan.crowd.filter;

import com.netflix.ribbon.proxy.annotation.Http;
import com.shanshan.crowd.constant.AccessPassResources;
import com.shanshan.crowd.constant.CrowdConstant;
import org.apache.http.protocol.RequestContent;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.result.view.RequestContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Date;
import java.util.Map;

/**
 * @Description
 * @ClassName CrowdAccessFilter
 * @Author 山山大魔王
 * @Date 2022/7/30 9:47
 * @Version 1.0
 */
@Component
public class CrowdAccessFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取请求的path值
        String path = exchange.getRequest().getURI().getPath();

        // 2.更具pathValue判断当前请求是否对应可以直接放行的特定功能
        boolean containsResult = AccessPassResources.PASS_RES_SET.contains(path);

        if(containsResult){
            // 3.如果当前请求是可以直接放行的特定功能则放行
            return chain.filter(exchange);
        }

        // 4.判断当前请求是否是静态资源
        // 工具返回true：说明当前请求是静态资源请求
        // 工具返回false：说明当前请求不是可以放行的特定请求也不是静态资源
        if (AccessPassResources.judgeCurrentServletPathWetherStaticResource(path)){
            return chain.filter(exchange);
        }

        // 使用不了下级模块的 session  ×
        // 6.获取当前Session
        Mono<WebSession> sessionMono = exchange.getSession();
        return sessionMono.flatMap(webSession -> {
            Map<String, Object> webSessionAttributes = webSession.getAttributes();
            // 7.尝试从session中获取已经登录的用户
            Object loginMember = webSessionAttributes.get(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
            // 8.判断loginMember是否为空
            if (loginMember == null) {
                webSessionAttributes.put(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().setLocation(URI.create("/auth/member/to/login/page"));
                return response.setComplete();
            }
            return chain.filter(exchange);
        });
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
